package com.cyan.app.workflow.activity.BMS;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Spinner;
import com.android.volley.VolleyError;
import com.cyan.app.workflow.AppData;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.base.activity.BaseActivity;
import com.cyan.app.workflow.bean.BaseBean;
import com.cyan.app.workflow.bean.BmsBarcodeBean;
import com.cyan.app.workflow.bean.ProssBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.customview.PullDownView;
import com.cyan.app.workflow.customview.PullDownView.OnPullDownListener;
import com.cyan.app.barcode.CaptureActivity;
import com.cyan.app.workflow.customview.ShowTipDialog;
import com.cyan.app.workflow.util.AppUtils;
import com.cyan.app.workflow.util.network.CommHttpListener;
import com.cyan.app.workflow.util.network.VolleyUtil;

import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.widget.ArrayAdapter;
/**
 * Created by DXW on 2015/11/24.
 */
public class BarcodeRecieveScanActivitiy extends BaseActivity implements OnPullDownListener, AdapterView.OnItemClickListener {
    public static final String TAG = "BarcodeRecieveScanActivitiy";
    private TextView mTextView;
    private Button mButton;
    private RelativeLayout mRelativeLayout;
    private ListView mannoinfo_lv;
    private PullDownView mPullDownView;
    private Button buttonScan;
    private Button buttonconfirm;

    private  BmsBarcodeInfo bmsBarcodeInfo;
    private EditText editBarcode;
    private EditText mEditTextManqty;
    private List<ProssBean.WorkProcudure> mProssBeans = new ArrayList<ProssBean.WorkProcudure>();
   private  ArrayList<String> listProssName  = new ArrayList<String>();
    private  Spinner spinner1;

    private EditText editItemNumber;
    private EditText editItemName;
    private  EditText editItemSpec;
    private  EditText editQty;
    private  EditText editProcedureName;
    private  EditText editOrder;
    private  ShowTipDialog showdialog = new ShowTipDialog();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bms_barcoderecscan);
        editBarcode = (EditText)findViewById(R.id.barcode_fin);
        editItemNumber  = (EditText)findViewById(R.id.bms_barcodefin_itemnumber);
        editProcedureName  = (EditText)findViewById(R.id.bms_barcodefin_procedure);
        editItemName  = (EditText)findViewById(R.id.bms_barcodefin_itemname);
        editItemSpec = (EditText)findViewById(R.id.bms_barcodefin_itemspec);
        editQty = (EditText)findViewById(R.id.bms_barcoderec_qty);
        editOrder = (EditText)findViewById(R.id.bms_barcodefin_manno);

        editItemNumber.setInputType(InputType.TYPE_NULL);
        editItemNumber.setTextColor(Color.GRAY);

        editProcedureName.setInputType(InputType.TYPE_NULL);
        editProcedureName.setTextColor(Color.GRAY);

        editItemName.setInputType(InputType.TYPE_NULL);
        editItemName.setTextColor(Color.GRAY);

        editItemSpec.setInputType(InputType.TYPE_NULL);
        editItemSpec.setTextColor(Color.GRAY);
        editQty.setInputType(InputType.TYPE_NULL);
        editQty.setTextColor(Color.GRAY);

        editOrder.setInputType(InputType.TYPE_NULL);
        editOrder.setTextColor(Color.GRAY);


        spinner1 = (Spinner) findViewById(R.id.pross_spinner);

        initData();
        initView();
        editBarcode.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //当actionId == XX_SEND 或者 XX_DONE时都触发
                //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
                //注意，这是一定要判断event != null。因为在某些输入法上会返回null。
                if ((event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {

                    getBmsBarocdeInfo(editBarcode.getText().toString());

                    return true;
                }
                return false;
            }
        });


        buttonconfirm = (Button)findViewById(R.id.bms_btn_confirm);
        buttonconfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String result = null;
                try {
                    if(!AppData.getInstance().isUserLogin()) return;
                    Map<String, String> params = new HashMap<String, String>();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("FactoryID", HttpConfig.Main_FactoryID);
                    jsonObject.put("UserNo", AppData.getInstance().getUserId());
                    jsonObject.put("Connectstring", AppData.getInstance().getConnectstring());
                    jsonObject.put("Barcode", editBarcode.getText().toString( ));

                    if(mProssBeans.size()>0) {
                        jsonObject.put("ProcedureNo", mProssBeans.get(spinner1.getSelectedItemPosition()).getProcedureNo());
                    }
                    params.put("paramstr", jsonObject.toString());
                    params.put("action", "BmsRecieveScan");
                    showdialog.showDialog(BarcodeRecieveScanActivitiy.this);
                    VolleyUtil.sendStringRequestByGet(BarcodeRecieveScanActivitiy.this, HttpConfig.HTTP_MAIN_API_URL, TAG, params, BaseBean.class, new CommHttpListener<BaseBean>() {
                        @Override
                        public void onSuccess(BaseBean baseBean) {
                            AppUtils.showTip(BarcodeRecieveScanActivitiy.this, baseBean.getMsg());
                            editBarcode.setText("");
                            editItemNumber.setText("");
                            editItemName.setText("");
                            editQty.setText("");
                            editProcedureName.setText("");
                            showdialog.closeDialog();
                        }



                        @Override
                        public void onCodeError(int code, String msg) {
                            AppUtils.showTip(BarcodeRecieveScanActivitiy.this, msg);
                            showdialog.closeDialog();
                        }

                        @Override
                        public void onVolleyError(VolleyError volleyError) {
                            AppUtils.showTip(BarcodeRecieveScanActivitiy.this, R.string.network_error);
                            showdialog.closeDialog();
                        }

                        @Override
                        public void onException(Exception e) {
                            AppUtils.showTip(BarcodeRecieveScanActivitiy.this, R.string.network_error);
                            showdialog.closeDialog();
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                    AppUtils.showTip(BarcodeRecieveScanActivitiy.this, "执行失败，请联系IT人员");
                    showdialog.closeDialog();
                }


            }
        });

        buttonScan = (Button) findViewById(R.id.bms_barcoderec_scan);
        buttonScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(BarcodeRecieveScanActivitiy.this, CaptureActivity.class), 0x0002);
            }
        });

    }
    //初始化控件
    private void initData() {
        //mMannoBeans = MannoLabBean.get(this).getMannos();
        //获取工序信息
        String result = null;
        try {
            if(!AppData.getInstance().isUserLogin()) return;
            Map<String, String> params = new HashMap<String, String>();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("FactoryID", HttpConfig.Main_FactoryID);
            jsonObject.put("UserNo", AppData.getInstance().getUserId());
            jsonObject.put("Connectstring", AppData.getInstance().getConnectstring());
            params.put("action", "GetPross");
            params.put("paramstr", jsonObject.toString());
            VolleyUtil.sendStringRequestByGet(BarcodeRecieveScanActivitiy.this, HttpConfig.HTTP_MAIN_API_URL, TAG, params, ProssBean.class, new CommHttpListener<ProssBean>() {
                @Override
                public void onSuccess(ProssBean prossBean) {

                    //  mProssBeans = new Gson().fromJson(result, new TypeToken<List<ProssBean>>() {
//                    }.getType());
                    mProssBeans = prossBean.getResult();
                    for(ProssBean.WorkProcudure obj : mProssBeans){
                        listProssName.add(obj.getProcedureName());
                    }

                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(BarcodeRecieveScanActivitiy.this,android.R.layout.simple_spinner_item, listProssName);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spinner1 .setAdapter(adapter);
                    spinner1.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view,
                                                   int pos, long id) {

                            //String[] languages = getResources().getStringArray(R.array.languages);
                           // AppUtils.showTip(BarcodeRecieveScanActivitiy.this,  mProssBeans.get(pos).getProcedureNo());
                        }
                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                            // Another interface callback
                        }
                    });
                }

                @Override
                public void onCodeError(int code, String msg) {
                    AppUtils.showTip(BarcodeRecieveScanActivitiy.this, msg);
                }

                @Override
                public void onVolleyError(VolleyError volleyError) {
                    AppUtils.showTip(BarcodeRecieveScanActivitiy.this, R.string.network_error);
                }

                @Override
                public void onException(Exception e) {
                    AppUtils.showTip(BarcodeRecieveScanActivitiy.this, R.string.network_error);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
            AppUtils.showTip(BarcodeRecieveScanActivitiy.this, "执行失败，请联系IT人员");
        }


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0x0002 && resultCode == RESULT_OK) {
            String result = "";
            if(data != null) {
                result = data.getStringExtra("result");
                getBmsBarocdeInfo(result);
            }

        }
    }

    private void getBmsBarocdeInfo(String barcode){
        String result = null;
        try {
            Map<String, String> params = new HashMap<String, String>();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Barcode", barcode);
            jsonObject.put("FactoryID", HttpConfig.Main_FactoryID);
            jsonObject.put("UserNo", AppData.getInstance().getUserId());
            jsonObject.put("Connectstring", AppData.getInstance().getConnectstring());
            if(mProssBeans.size()>0) {
                jsonObject.put("ProcedureNo", mProssBeans.get(spinner1.getSelectedItemPosition()).getProcedureNo());
            }

            params.put("action", "GetRecieveBarcode");
            params.put("paramstr", jsonObject.toString());
            showdialog.showDialog(BarcodeRecieveScanActivitiy.this);
            VolleyUtil.sendStringRequestByGet(BarcodeRecieveScanActivitiy.this, HttpConfig.HTTP_MAIN_API_URL, TAG, params, BmsBarcodeBean.class, new CommHttpListener<BmsBarcodeBean>() {
                public void onSuccess(BmsBarcodeBean bmsBarcodeBean) {
                    List<BmsBarcodeBean.BmsBarcode> bmsBarcodes = new  ArrayList<BmsBarcodeBean.BmsBarcode>();
                    bmsBarcodes = bmsBarcodeBean.getResult();
                    if(bmsBarcodes.size()>0){

                      //  editBarcode.setText(bmsBarcodes.get(0).getBarcode());
                        editItemNumber.setText(bmsBarcodes.get(0).getItemNumber());
                        editItemName.setText(bmsBarcodes.get(0).getItemName());
                        editQty.setText(bmsBarcodes.get(0).getQty().toString());
                        editOrder.setText(bmsBarcodes.get(0).getOrderNumber());
                        editProcedureName.setText(bmsBarcodes.get(0).getProcedureName());
                    }
                    else{

                        AppUtils.showTip(BarcodeRecieveScanActivitiy.this, "无效条码，请扫码正确的条码");
                        editBarcode.setText("");
                    }
                    showdialog.closeDialog();
                }

                @Override
                public void onCodeError(int code, String msg) {
                    AppUtils.showTip(BarcodeRecieveScanActivitiy.this, msg);
                    editBarcode.setText("");
                    showdialog.closeDialog();
                }

                @Override
                public void onVolleyError(VolleyError volleyError) {
                    AppUtils.showTip(BarcodeRecieveScanActivitiy.this, R.string.network_error);
                    editBarcode.setText("");
                    showdialog.closeDialog();
                }

                @Override
                public void onException(Exception e) {
                    AppUtils.showTip(BarcodeRecieveScanActivitiy.this, R.string.network_error);
                    editBarcode.setText("");
                    showdialog.closeDialog();
                }
            });
        }catch (Exception e){
            e.printStackTrace();
            AppUtils.showTip(BarcodeRecieveScanActivitiy.this, "执行失败，请联系IT人员");
        } finally {
           //
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
       // adapter.notifyDataSetChanged();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    private void initView(){
        titleBar();
        /*
		 * 1.使用PullDownView 2.设置OnPullDownListener 3.从mPullDownView里面获取ListView
		 */

    }

    private void titleBar() {
        mTextView =(TextView)findViewById(R.id.top_title_info);
        mTextView.setText("在制接收");
        Button back = (Button) findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                finish();
            }
        });
        mButton = (Button)findViewById(R.id.top_title_refres_with_icon);
        mButton.setVisibility(View.VISIBLE);
//        mButton.setText("添加");
//        mButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent();
//                intent.setClass(BarcodeFinScanActivitiy.this, GdlzNewActivity.class);
//                //startActivity(intent);
//                startActivityForResult(intent,0x0001);
//            }
//        });

        mRelativeLayout =(RelativeLayout) findViewById(R.id.bms_barcodefin_scan_footer);
        mRelativeLayout.setVisibility(View.VISIBLE);
    }

    /**
     * listview单项点击事件
     */
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // Toast.LENGTH_SHORT).show();
    }

    /**
     * listview刷新
     */
    public void onRefresh() {

    }

    /**
     * listview更多
     */
    public void onMore() {
      return;
    }


    class BmsBarcodeInfo extends BaseBean {
        private int Wareqty;
        private String Manno;
        private String Itnbr;

        public String getManno() {
            return Manno;
        }
        public void setManno(String manno) {
            Manno = manno;
        }

        public String getItnbr() {
            return Itnbr;
        }
        public void setItnbr(String itnbr) {
            Itnbr = itnbr;
        }

        public int getWareqty() {
            return Wareqty;
        }
        public void setWareqty(int manqty) {
            Wareqty = manqty;
        }
    }
}
